package com.yxkj.syh.app.huarong.activities.orders.detail.status0;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.syh.app.basic.base.BaseActivity;
import com.syh.app.basic.utils.AppUtil;
import com.syh.app.basic.utils.ComUtil;
import com.syh.app.basic.utils.Loog;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.views.ImageWatcher;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.activities.creat.add_goods.AddGoodsActivity;
import com.yxkj.syh.app.huarong.activities.creat.address.edit.EditAddressActivity;
import com.yxkj.syh.app.huarong.activities.creat.edit.EditOrderActivity;
import com.yxkj.syh.app.huarong.activities.orders.detail.status_other.OrderOtherStatusActivity;
import com.yxkj.syh.app.huarong.adps.AddedGoodsAdp;
import com.yxkj.syh.app.huarong.bean.Goods;
import com.yxkj.syh.app.huarong.bean.OrderInfo;
import com.yxkj.syh.app.huarong.bean.UserMainInfo;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.databinding.ActivityOrderWaitBinding;

import java.util.ArrayList;
import java.util.List;

/**
 * 待发货
 */
@Route(path = ArouterPath.ORDER_WAIT_ACTIVITY)
public class OrderWaitActivity extends BaseActivity<ActivityOrderWaitBinding, OrderWaitVM> {


    @Autowired
    long orderId;

    AddedGoodsAdp mAddedGoodsAdp;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_order_wait;
    }

    @Override
    protected int getViewModelId() {
        return BR.orderWaitVM;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (orderId <= 0) finish();

        mVDBinding.titleView.setLeftOnClickListener(v -> finish());

        mAddedGoodsAdp = new AddedGoodsAdp();
        mAddedGoodsAdp.setOnClick(goods -> {
            addGoods(goods);
        });
        mVDBinding.rvGoods.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        mVDBinding.rvGoods.setAdapter(mAddedGoodsAdp);

        mVDBinding.tvAddGoods.setOnClickListener(v -> {
            addGoods(null);
        });
        mVDBinding.rlFrom.setOnClickListener(v -> {
            Intent intent = new Intent(OrderWaitActivity.this, EditAddressActivity.class);
            intent.putExtra("userMainInfo", mViewModel.mldOrderDetail.getValue().getOrderInfo().getStartLocation());
            startActivityForResult(intent, 0x1a);
        });
        mVDBinding.rlTo.setOnClickListener(v -> {
            Intent intent = new Intent(OrderWaitActivity.this, EditAddressActivity.class);
            intent.putExtra("userMainInfo", mViewModel.mldOrderDetail.getValue().getOrderInfo().getEndLocation());
            startActivityForResult(intent, 0x2a);
        });

        mVDBinding.tvCopyID.setOnClickListener(v -> {
                    if (AppUtil.copy2Clipboard(OrderWaitActivity.this, mViewModel.mldOrderDetail.getValue().getOrderInfo().getNo())) {
                        Tooast.success("已复制订单编号到粘贴板");
                    }
                }
        );
        mVDBinding.btnConfirm.setOnClickListener(v -> {
            if (mViewModel.mldOrderDetail.getValue() != null) {
                if (mAddedGoodsAdp.getData().size() > 0) {
                    Intent intent = new Intent(OrderWaitActivity.this, EditOrderActivity.class);
                    intent.putExtra("orderInfo", mViewModel.mldOrderDetail.getValue().getOrderInfo());
                    startActivityForResult(intent, 0x3a);
                } else {
                    Tooast.normalInfo("请添加货品");
                }
            }
        });

        mVDBinding.ivQrCode.setOnClickListener(v -> {
            Bitmap bitmap = ComUtil.createQRCode(mViewModel.mldOrderDetail.getValue().getOrderInfo().getNo(),400);
            new ImageWatcher(OrderWaitActivity.this).show(bitmap);
        });

    }

    @Override
    protected void initData() {
        mViewModel.getOrderDetail(orderId);
    }

    @Override
    protected void initObservers() {
        super.initObservers();
        mViewModel.mldOrderDetail.observe(this, orderDetail -> {
            setFrom(orderDetail.getOrderInfo().getStartLocation());
            setTo(orderDetail.getOrderInfo().getEndLocation());
            setGoods(orderDetail.getOrderInfo().getDetails());
            setBuyInfo(orderDetail.getOrderInfo());
            setOrder(orderDetail.getOrderInfo());
        });

        mViewModel.mldEditGoods.observe(this, goods -> {
            setGoods(goods);
        });
    }

    private void setFrom(UserMainInfo from) {
        mVDBinding.tvFromPerson.setText(from.getLinkman());
        mVDBinding.tvFromMobile.setText(from.getMobile());
        mVDBinding.tvFromAddress.setText(from.getArea().replace("/","") + from.getAddress());
    }

    private void setTo(UserMainInfo to) {
        mVDBinding.tvToPerson.setText(to.getLinkman());
        mVDBinding.tvToMobile.setText(to.getMobile());
        mVDBinding.tvToAddress.setText(to.getArea().replace("/","") + to.getAddress());
    }

    private void setGoods(List<Goods> goods) {
        for (Goods temp : goods) {
            temp.setAdded(true);
            temp.setLableStatus(0);
        }
        mAddedGoodsAdp.setIsCreator(mViewModel.ofCreatBySelf.get());
        mAddedGoodsAdp.setNewData(goods);
    }


    private void setBuyInfo(OrderInfo orderInfo) {
        mVDBinding.tvSupplier.setText(orderInfo.getSupplierName());
        mVDBinding.tvBuyer.setText(orderInfo.getSalesman().getRealName());
        mVDBinding.tvFactory.setText(orderInfo.getEndLocation().getName());
    }

    private void setOrder(OrderInfo orderInfo) {
        mVDBinding.tvOrderId.setText(orderInfo.getNo());
        mVDBinding.tvCreatTime.setText(orderInfo.getCreateTime());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x1a) {
                UserMainInfo from = (UserMainInfo) data.getSerializableExtra("userMainInfo");
                mViewModel.mldOrderDetail.getValue().getOrderInfo().setStartLocation(from);
                setFrom(from);
            } else if (requestCode == 0x2a) {
                UserMainInfo to = (UserMainInfo) data.getSerializableExtra("userMainInfo");
                mViewModel.mldOrderDetail.getValue().getOrderInfo().setEndLocation(to);
                setTo(to);
            } else if (requestCode == 0x3a) {//发货成功
                finish();
            } else if (requestCode == 0x4a) {
                Goods goods = (Goods) data.getSerializableExtra("goods");
                int operate = data.getIntExtra("operate", -1);

                List<Goods> tempList = new ArrayList<>();
                tempList.addAll(mAddedGoodsAdp.getData());

                if (operate == 0) {//添加
                    tempList.add(goods);
                } else if (operate == 1) {//移除
                    for (Goods temp : tempList) {
                        Loog.d("OrderWaitActivity", "temp.getProductId() = " + temp.getProductId());
                        Loog.d("OrderWaitActivity", "goods.getProductId() = " + goods.getProductId());
                        if (temp.getProductId().equals(goods.getProductId())) {
                            Loog.d("OrderWaitActivity", "remove = " + goods.getProductId());
                            tempList.remove(temp);
                            break;
                        }
                    }
                } else if (operate == 2) {//编辑
                    for (int i = 0; i < tempList.size(); i++) {
                        Goods temp = tempList.get(i);
                        if (temp.getProductId().equals(goods.getProductId())) {
                            temp.setPackages(goods.getPack().intValue());
                            temp.setQuantity(goods.getWeight());
                            break;
                        }
                    }
                }

                mViewModel.editGoods(tempList);
            }
        } else {
            if (requestCode == 0x3a) {//未发货  但可能修改了订单信息
                mViewModel.getOrderDetail(orderId);
            }
        }
    }


    private void addGoods(Goods clickedGoods) {

        ArrayList<String> added = new ArrayList<>();
        for (Goods goods : mAddedGoodsAdp.getData()) {
            String tag = goods.getProductId() + "";

            added.add(tag);
        }
        Intent intent = new Intent(OrderWaitActivity.this, AddGoodsActivity.class);
        intent.putStringArrayListExtra("added", added);
        if (clickedGoods != null) {
            intent.putExtra("preSelectedGoods", clickedGoods);
        }
        startActivityForResult(intent, 0x4a);
    }

}
